package com.john.pplay.common;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.john.pplay.R;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class FileExploerAdapter extends RecyclerView.Adapter<FileExploerAdapter.MViewHolder> implements View.OnClickListener {

    private List<File> list;
    private Context context;
    private ItemListener listener;

    public FileExploerAdapter(Context con){
        context = con;
        list = new LinkedList<>();
    }
    public FileExploerAdapter(Context con, List<File> l){
        context = con;
        list = l;
    }

    public void setListener(ItemListener lstn){
        listener = lstn;
    }
    public void update(List<File> l){
        list = l;
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public MViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_file,parent,false);
        return new MViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MViewHolder holder, int position) {
        File file = list.get(position);
        holder.viewName.setText(file.getName());
        if (file.isDirectory()){
            holder.viewType.setBackgroundResource(R.drawable.ic_folder);
        }else{
            holder.viewType.setBackgroundResource(R.drawable.ic_play_arrow);
        }

        holder.itemView.setTag(position);
        holder.itemView.setOnClickListener(this);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onClick(View view) {
        listener.onItemClick((int)view.getTag());
    }

    public class MViewHolder extends RecyclerView.ViewHolder{

        public AppCompatImageView viewType;
        public TextView viewName;

        public MViewHolder(View itemView) {
            super(itemView);
            viewType = itemView.findViewById(R.id.imv_file_type);
            viewName = itemView.findViewById(R.id.tv_file_name);
        }
    }
}
